import { LoginData } from '@/types/index';
import { to } from 'await-to-js';
import defAva from '@/static/profile.jpg';
import { useIMStore } from '@/store/modules/im';
import { useSocketStore } from '@/store/modules/webSocket';
import { cacheAvatar } from '@/utils/index';

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const refreshToken = ref(getRefreshToken());
  const userId = ref<string | number>(null);
  const phoneNumber = ref(null);
  const userName = ref(null);
  const nickName = ref(null);

  const avatar = ref(null);
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const refreshStatus = ref<boolean>(true);
  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    // if(!getToken()){
    //   logout()
    // }

    userInfo.tenantId = import.meta.env.VITE_APP_TENANT_ID;
    userInfo.clientId = import.meta.env.VITE_APP_CLIENT_ID;

    const [err, res] = await to(uni.$u.http.post(`/auth/login`, userInfo, { header: { isEncrypt: true } }));

    if (res) {
      const data = res.data;
      setToken(data.access_token);
      setRefreshToken(data.refresh_token);
      token.value = data.access_token;
      refreshToken.value = data.refresh_token;
      useSocketStore().initSocket();
      initSSE();
      getInfo();
      getAllMsg();
      return Promise.resolve();
    }
    return Promise.reject(err);
  };
  //微信code 登录
  const wxLogin = async (): Promise<void> => {
    const loginRes = await uni.login({ provider: 'weixin' });
    const loginForm = ref<LoginData>({
      appid: uni.getAccountInfoSync().miniProgram.appId,
      xcxCode: loginRes.code,
      grantType: 'xcx'
    } as LoginData);
    return login(loginForm.value);
  };
  // 获取用户信息
  const getInfo = async (): Promise<void> => {

    const [err, res] = await to(uni.$u.http.get(`/system/appUser/profile`));
    if (res) {
      const data = res.data;
      const user = data.user;
      const profile = user.avatarUrl == '' || user.avatarUrl == null ? defAva : user.avatarUrl;

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles;
        permissions.value = data.permissions;
      } else {
        roles.value = ['ROLE_DEFAULT'];
      }
      phoneNumber.value = user.phonenumber;
      userName.value = user.userName;
      nickName.value = user.nickName == '' || user.nickName == null ? '请完善信息' : user.nickName;
      avatar.value = profile;
      userId.value = user.userId;
      return Promise.resolve(res);
    }
    return Promise.reject(err);
  };
  // 获取用户信息
  const getAllMsg = async () => {
    const [err, res] = await to(uni.$u.http.get(`/system/instantMessaging/notReadMessageCount`));
    if (res.data) {
      Object.keys(res.data).forEach(key => {
        useIMStore().set(key, res.data[key]);
      });
    }

  };


  // 注销
  const logout = async (): Promise<void> => {
    await closeSSE();
    useSocketStore().closeWebSocket();
    await uni.$u.http.post(`/auth/logout`);
    token.value = '';
    refreshToken.value = '';
    roles.value = [];
    permissions.value = [];

    removeToken();
    removeRefreshToken();
  };
  return {
    userId,
    token,
    nickName,
    userName,
    phoneNumber,
    avatar,
    roles,
    permissions,
    refreshStatus,
    login,
    wxLogin,
    getInfo,
    logout,
    getAllMsg
  };
}, { unistorage: { key: 'user', paths: ['userId','avatar', 'roles', 'permissions', 'refreshStatus'] } });

export default useUserStore;

